// pages/deviceSetMealManage/deviceSetMealManage.js
var area = require('../../data/area')
var g = 0,
  l = 0
var app = getApp()
var api = require("../../config/api.js")
var comm = require("../../utils/comm.js")
var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    useNumber: '',
    marketMoney: '',
    money: '',
    address: '',
    startDate: '2018-09-27',
    endDate: '2018-12-27',

    inputShowed: false,
    inputVal: "",

    startNum: 1, //页数

    total: '0',

    search: false, //判断模糊查询方法

    tabs: ["套餐列表", "新增套餐", ],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,

    toast1Hidden: true,
    modalHidden: true,
    modalHidden2: true,
    notice_str: '',

    files: [],
    files1: [],

    myAgentList: {
      hasMore: true,
      list: [],
      listSize: 0
    },

    curisOnSale: '0',

    showMessage: false,
    messageContent: '',
    showDistpicker: false,

    categoryall: [], //所有分类
    categoryscond: [], //二级分类
    Categoryl1: [],
    Categorycodel1: [],
    CategoryIndexl1: '',
    Categoryl2: [],
    Categorycodel2: [],
    CategoryIndexl2: '',

    onsale: 1,
    isnew: 1,

    primaryPicUrl: '', //主图
    listPicUrl: '', //列表图

  },


  //选择开始时间
  bindStartDateChange: function (e) {
    this.setData({
      startDate: e.detail.value
    })
  },

  //选择结束时间
  bindEndDateChange: function (e) {
    this.setData({
      endDate: e.detail.value
    })
  },


  //设备套餐上下架
  ononsale: function() {
    if (this.data.onsale == 0) {
      this.setData({
        onsale: 1
      })
    } else {
      this.setData({
        onsale: 0
      })
    }
  },


  // 搜索框状态
  showInput: function() {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function() {
    this.setData({
      inputVal: "",
      inputShowed: false,
      search: false
    });
    this.onLoad();

  },
  clearInput: function() {
    this.setData({
      inputVal: ""
    });
  },
  inputTyping: function(e) {
    this.setData({
      inputVal: e.detail.value
    });
  },


  //搜索
  searInput: function(e) {
    var _that = this
    console.log(_that.data.inputVal)
    wx.showLoading({
      title: '搜索中',
    })
    if (_that.data.inputVal.length != 0) {
      wx.request({
        url: api.GoodsDevicePagList + '?current=1&size=10',
        data: {
          title: _that.data.inputVal,
          current: "1", //请求第一页
          size: "10"
        },
        method: 'POST',
        header: {
          'Accept': 'application/json',
          'ACCESS-TOKEN': wx.getStorageSync('token')
        },
        success: function(res) {
          console.log(res.data)
          wx.hideLoading();
          if (res.data.code == '1') {
            var listSize = res.data.obj.records.length;
            console.log('listSize=' + listSize);
            var newData = _that.data.myAgentList.list;
            newData = res.data.obj.records;
            var total1 = res.data.obj.total;
            var newList = {};
            //当长度小于10表示没有下页数据了
            if (listSize < 10) {
              newList.hasMore = false;
            } else {
              newList.hasMore = true;
            }
            newList.list = newData;
            console.log('newData=' + newData);
            newList.listSize = listSize;
            _that.setData({
              myAgentList: newList
            });
            console.log('myAgentList=' + _that.data.myAgentList);
            _that.setData({
              startNum: 2,
              total: total1,
              search: true
            });

            console.log("newList.list=" + newList.list)

            if (newList.list.length == 0) {
              wx.showModal({
                title: '提示',
                content: "抱歉！你搜索的商品不存在！",
                confirmColor: "#43CBC9",
                showCancel: false,
                success: function(res) {
                  if (res.confirm) {
                    console.log('用户点击确定')
                    _that.hideInput()
                  }
                }
              });
            }



          } else {
            // util.msg("错误", res.data.msg)
            console.log("网络不通，数据不成功")
          }
        },
        fail: function(res) {
          wx.hideLoading();
          console.log(res.data)
          // util.msg("错误", "通讯失败")
        }
      })

    } else {
      wx.showToast({
        title: "输入内容不能为空",
        icon: 'none',
        duration: 2000
      });
    }

  },

  //  点击开始日期组件确定事件  
  bindStartDateChange: function(e) {
    console.log(e.detail.startDate)
    this.setData({
      startDate: e.detail.value
    })
  },

  //  点击结束日期组件确定事件  
  bindEndDateChange: function(e) {
    console.log(e.detail.startDate)
    this.setData({
      endDate: e.detail.value
    })
  },

  //上拉刷新列表数据
  hotActivityLoadMore: function(e) {
    var _that = this;
    //判断是否还有下一页
    if (_that.data.myAgentList.hasMore == true) {
      wx.showLoading({
        title: '加载中',
      })
      var pageNum = _that.data.startNum
      var _url = api.GoodsDevicePagList + '?current=' + pageNum + '&size=5';
      wx.request({
        url: _url,
        data: {

        },
        method: 'POST',
        header: {
          'Accept': 'application/json',
          'ACCESS-TOKEN': wx.getStorageSync('token')
        },
        success: function(res) {
          console.log(res.data)
          if (res.data.code == "1") {
            console.log("网络通，数据成功")
            wx.hideLoading();
            var listSize = res.data.obj.records.length;
            var newData = _that.data.myAgentList.list;
            //concat是在原有基础上进行增加
            newData = newData.concat(res.data.obj.records);
            var newList = {};
            //当长度等于于0表示当前没有数据，停止
            if (listSize == 0) {
              newList.hasMore = false;
              wx.showToast({
                title: "已加载全部列表",
                icon: 'none',
                duration: 2000
              });
              return;
              //当长度小于5表示没有下页数据了
            } else if (listSize < 5) {
              wx.showToast({
                title: "已加载全部列表",
                icon: 'none',
                duration: 2000
              });
              newList.hasMore = false;
            } else {
              newList.hasMore = true;
            }
            newList.list = newData;
            newList.listSize = listSize;
            _that.setData({
              myAgentList: newList
            });

            _that.setData({
              startNum: pageNum + 1 //页数加1
            })
          } else {
            // util.msg("错误", res.data.msg)
            console.log("网络不通，数据不成功")
          }

        },
        fail: function(res) {
          console.log(res.data)
          // util.msg("错误", "通讯失败")
          console.log("失败")
        }
      })
    } else {
      wx.showToast({
        title: "已加载全部列表",
        icon: 'none',
        duration: 2000
      });
    }
  },

  //提交新增商品
  formSubmit: function(e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否确认提交',
      confirmColor: "#43CBC9",
      success: (res) => {
        wx.showLoading({
          title: '加载中',
        })

        if (res.confirm) {
          console.log('for发生了submit事件，携带数据为：', e.detail.value);
          if (e.detail.value.title == '') {
            wx.showToast({
              title: "请填写套餐名称!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.useNumber == '') {
            wx.showToast({
              title: "请填写服务次数!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (!/^[0-9]*[1-9][0-9]*$/.test(e.detail.value.useNumber)){
            wx.showToast({
              title: "服务次数必须是正整数!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.marketMoney == '') {
            wx.showToast({
              title: "请填写市场价格!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (!/^\d+(\.\d{1,2})?$/.test(e.detail.value.marketMoney)) {
            wx.showToast({
              title: "市场价格必须是两位小数的价格!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.money == '') {
            wx.showToast({
              title: "请填写套餐价格!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (!/^\d+(\.\d{1,2})?$/.test(e.detail.value.money)) {
            wx.showToast({
              title: "套餐价格必须是两位小数的价格!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.startDate == '') {
            wx.showToast({
              title: "请填写开始时间!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.endDate == '') {
            wx.showToast({
              title: "请填写结束时间!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.address == '') {
            wx.showToast({
              title: "请填写地址!",
              icon: 'none',
              duration: 2000
            });
            return false;
          }

          wx.request({
            url: api.GoodsDeviceAdd,
            data: {
              title: e.detail.value.title,
              useNumber: e.detail.value.useNumber,
              money: e.detail.value.money,
              marketMoney: e.detail.value.marketMoney,
              startDate: that.data.startDate,
              endDate: that.data.endDate,
              address: e.detail.value.address
            },
            method: 'POST',
            header: {
              'Accept': 'application/json',
              'ACCESS-TOKEN': wx.getStorageSync('token')
            },
            success: function(res) {
              wx.hideLoading();
              if (res.data.success) {
                wx.showModal({
                  title: '提示',
                  content: "添加套餐成功!",
                  confirmColor: "#43CBC9",
                  showCancel: false,
                  success: function(res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                      console.log('开始时间:' + e.detail.value.startDate);
                      console.log('结束时间:' + e.detail.value.endDate);
                      that.clearData()
                      that.setData({
                        activeIndex: 0
                      })
                      that.onLoad()
                    }
                  }
                });
                wx.hideLoading();
              } else {
                console.log("网络不通，数据不成功!")
              }
            },
            fail: function() {
              wx.hideLoading();
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 2000
              });
            },
          })

        } else if (res.cancel) {
          console.log('用户点击取消')
          wx.hideLoading();
        }
      }
    })
  },

  formrs: function() {
    this.clearData()
    wx.showToast({
      title: '清空成功！',
      icon: 'none'
    })
  },

  //清空套餐填写数据
  clearData: function() {
    this.setData({
      title: '',
      useNumber: '',
      marketMoney: '',
      money: '',
      address: '',
      startDate: '',
      endDate: ''
    });
  },

  //修改套餐状态为上架
  sell: function(e) {
    var that = this;
    console.log("that.data.curisOnSale=" + that.data.curisOnSale)

    var ID = e.target.id;

    if (that.data.curisOnSale == '0') {
      wx.showModal({
        title: '提示',
        content: '是否确认上架该套餐？',
        confirmColor: "#43CBC9",
        success: (res) => {
          wx.showLoading({
            title: '加载中',
          })
          if (res.confirm) {
            console.log('用户点击确定');

            wx.request({
              url: api.GoodsDeviceEnSale + ID,
              data: {},
              method: 'GET',
              header: {
                'Accept': 'application/json',
                'ACCESS-TOKEN': wx.getStorageSync('token')
              },
              success: (res) => {
                wx.showLoading({
                  title: '加载中',
                })
                if (res.data.success) {
                  that.setData({
                    curisOnSale: '1'
                  });
                  wx.hideLoading();
                  console.log("that.data.curisOnSale" + that.data.curisOnSale);
                  if (res.data.code == '1') {
                    wx.showModal({
                      title: '提示',
                      content: "套餐已成功上架!",
                      confirmColor: "#43CBC9",
                      showCancel: false,
                      success: function(res) {
                        if (res.confirm) {
                          console.log('用户点击确定');
                          that.onLoad();
                        }
                      }
                    });
                    wx.hideLoading();
                  } else {
                    console.log("网络不通，数据不成功");
                  }
                }
              },
              fail: function() {
                wx.hideLoading();
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 2000
                });
              },
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
            wx.hideLoading();
          }
        }
      })
    } else {
      wx.showToast({
        title: "套餐已上架!",
        icon: 'none',
        duration: 3000
      });
    }
  },

  //管理设备套餐信息页面跳转
  maginfo: function(e) {
    wx.navigateTo({
      url: '/pages/deviceSetMealManage/deviceSetMealInfo?Id=' + e.currentTarget.id,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    that.setCatego();
    wx.setStorageSync('getimgUrl', '')
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });

    var _that = this
    var _url = api.GoodsDevicePagList + '?current=1&size=5';
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: _url,
      data: {

      },
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'ACCESS-TOKEN': wx.getStorageSync('token')
      },
      success: function(res) {
        console.log(res.data)
        wx.hideLoading();
        if (res.data.code == '1') {
          var listSize = res.data.obj.records.length;
          console.log('listSize=' + listSize);
          var newData = _that.data.myAgentList.list;
          newData = res.data.obj.records;
          var total1 = res.data.obj.total;
          var newList = {};
          //当长度小于5表示没有下页数据了
          if (listSize < 5) {
            newList.hasMore = false;
          } else {
            newList.hasMore = true;
          }
          newList.list = newData;
          console.log('newData=' + newData);
          newList.listSize = listSize;
          _that.setData({
            myAgentList: newList,
            total: total1
          });

          console.log('myAgentList=' + _that.data.myAgentList);

          _that.setData({
            startNum: 2
          })
        } else {
          // util.msg("错误", res.data.msg)
          console.log("网络通，数据不成功")
        }
      },
      fail: function(res) {
        wx.hideLoading();
        console.log(res.data)
        // util.msg("错误", "通讯失败")
      }
    })


  },

  tabClick: function(e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
  },



  //弹出确认框  
  modalTap: function(e) {
    this.setData({
      modalHidden: true
    })
  },
  confirm_one: function(e) {
    console.log(e);
    this.setData({
      modalHidden: true,
      toast1Hidden: false,
      notice_str: '提交成功'
    });
  },
  cancel_one: function(e) {
    console.log(e);
    this.setData({
      modalHidden: true,
      toast1Hidden: false,
      notice_str: '取消成功'
    });
  },
  //弹出提示框  
  modalTap2: function(e) {
    this.setData({
      modalHidden2: false
    })
  },
  modalChange2: function(e) {
    this.setData({
      modalHidden2: true
    })
  },
  toast1Change: function(e) {
    this.setData({
      toast1Hidden: true
    });
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.onLoad();

  },


  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },

  //获取一级分类信息
  getCatel1: function() {
    var that = this
    wx.request({
      url: api.GoodsCateGetOne,
      data: {},
      method: 'GET',
      header: {
        'Accept': 'application/json',
        'ACCESS-TOKEN': wx.getStorageSync('token')
      },
      success: function(res) {
        console.log(res.data)
        wx.hideLoading();
        if (res.data.code == '1') {
          var relsize = res.data.obj.categoryList.length;
          var categoryList = res.data.obj.categoryList;
          var Catl = []
          var Catco = []
          for (var i = 0; i < relsize; i++) {
            Catl = Catl.concat(categoryList[i].categoryName)
            Catco = Catco.concat(categoryList[i].id)
          }
          that.setData({
            Categoryl1: Catl,
            Categorycodel1: Catco
          })
        } else {
          console.log("网络通，数据不成功")
        }
      },
      fail: function(res) {
        wx.hideLoading();
        console.log(res.data)
      }
    })
  },

  //获取二级分类
  getCatel2: function(Id) {
    var that = this
    if (Id) {
      wx.request({
        url: api.GoodsCateGetById + Id,
        data: {},
        method: 'GET',
        header: {
          'Accept': 'application/json',
          'ACCESS-TOKEN': wx.getStorageSync('token')
        },
        success: function(res) {
          console.log(res.data)
          wx.hideLoading();
          if (res.data.code == '1') {
            var relsize = res.data.obj.currentSubCategory.length;
            var categoryList = res.data.obj.currentSubCategory;
            var Catl = [];
            var Catco = [];
            for (var i = 0; i < relsize; i++) {
              Catl = Catl.concat(categoryList[i].categoryName)
              Catco = Catco.concat(categoryList[i].id)
            }
            that.setData({
              Categoryl2: Catl,
              Categorycodel2: Catco
            })
          } else {
            console.log("网络通，数据不成功")
          }
        },
        fail: function(res) {
          wx.hideLoading();
          console.log(res.data)
        }
      })
    }
  },

  //获取商品分类的对象集合
  getAllGoodsCate: function(index) {
    var that = this
    comm.request(api.GoodsAllCate, {}, "GET").then(function(res) {
      if (res.success) {
        var catelist = res.obj
        that.setData({
          categoryall: catelist,
        })
        that.getCgetCateListfrs(index)
      }
    }).catch(function(res) {
      console.log("获取商品分类失败！")
    })
  },

  // 从所有集合中取出一分类
  getCgetCateListfrs: function(index) {
    var that = this
    var catelist = that.data.categoryall
    var relsize = that.data.categoryall.length
    var categoryscond = []
    var Catl = []
    var Catco = []
    for (var i = 0; i < relsize; i++) {
      Catl = Catl.concat(catelist[i].categoryName)
      Catco = Catco.concat(catelist[i].id)
    }
    categoryscond = categoryscond.concat(catelist[index].subGoodsCategoryList)
    that.setData({
      Categoryl1: Catl,
      Categorycodel1: Catco,
      categoryscond: categoryscond
    })

    that.getCateListIndex()
  },

  //根据一级参数index选择二级分类的集合
  getCateListIndex: function() {
    var that = this
    var categoryall = that.data.categoryscond
    var relsize = that.data.categoryscond.length
    var Catl = [];
    var Catco = [];
    for (var i = 0; i < relsize; i++) {
      Catl = Catl.concat(categoryall[i].categoryName)
      Catco = Catco.concat(categoryall[i].id)
    }
    that.setData({
      Categoryl2: Catl,
      Categorycodel2: Catco
    })
  },


  setCatego: function(g, l) {
    var that = this
    var g = g || 0
    var l = l || 0
    // //设置一级分类
    // that.getCatel1()
    // // 设置二级分类
    // that.getCatel2(this.data.Categorycodel1[g])
    that.getAllGoodsCate(g)
  },

  changeCate: function(e) {
    g = e.detail.value[0]
    l = e.detail.value[1]
    this.setCatego(g, l)
  },

  distpickerSure: function() {
    this.setData({
      CategoryIndexl1: g,
      CategoryIndexl2: l,
    })
    this.distpickerCancel()
  },

  showDistpicker: function() {
    this.setData({
      showDistpicker: true
    })
  },
  distpickerCancel: function() {
    this.setData({
      showDistpicker: false
    })
  },

  showMessage: function(text) {
    var that = this
    that.setData({
      showMessage: true,
      messageContent: text
    })
    setTimeout(function() {
      that.setData({
        showMessage: false,
        messageContent: ''
      })
    }, 3000)
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})